package com.lenovo.vctlclient;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;

import android.app.Activity;
import android.content.Context;

import com.lenovo.vctlclient.util.Log;

public class ActivityTracker {

	private Activity currentActivity = null;
	private static final String TAG="ActivityTracker";
	private AtomicReference<Activity> root = new AtomicReference<Activity>();
	private ArrayList<Activity> allocated = new ArrayList<Activity>();

	private ActivityTracker() {

	}

	private static ActivityTracker at = new ActivityTracker();
	private Context remedyctx = null;

	public static ActivityTracker getAT() {
		return at;
	}

	public void ActivityOnCreate(Activity currAct) {
		Log.d(TAG, "onCreate:"+currAct);
		currentActivity = currAct;
		allocated.remove(currAct);
		allocated.add(0, currAct);
	}

	public void ActivityOnDestroy(Activity destroyed) {
		if (destroyed == currentActivity) {
			int idx = allocated.indexOf(destroyed);
			if (idx != -1 && allocated.size() > idx + 1)
				currentActivity = allocated.get(idx + 1);
			else
				currentActivity = null;
		}
		allocated.remove(destroyed);
		if (allocated.size() == 1 && allocated.get(0) == root.get()) {
			allocated.clear();
			finishRoot();
		}
		if (allocated.isEmpty()) {
			finishRoot();
		}
	}
	
	
	private void finishRoot(){
		if(root.get()!=null){
			root.get().finish();
			root.set(null);
		}
	}
	
	public void ActivityOnKeyBack(Activity activity){
		if ((allocated.size() == 2 && allocated.get(1) == root.get())|| allocated.size()==1) {
			finishRoot();
		}
		
	}

	public Activity getPossibleTop() {
		if (currentActivity != null)
			return currentActivity;
		return root.get();
	}

	public void setRemedyCtx(Context ctx) {
		remedyctx = ctx;
	}

	public Context getAccessilbeCtx() throws ActivityNotRunning {
		if (getPossibleTop() != null)
			return getPossibleTop();
		if (remedyctx != null)
			return remedyctx;
		throw new ActivityNotRunning();
	}
}
